package com.yst.shader.feature.shimmer

import android.R.attr.*
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.interfaces.DraweeController
import com.facebook.imagepipeline.common.ResizeOptions
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.yst.shader.ext.FocusListener
import com.yst.shader.ext.HoverListener
import com.yst.shader.feature.widget.CanvasShimmerView
import com.yst.shader.feature.widget.SimpleImage
import com.yst.shader.widget.UriImageView


/**
 * @author: xuyujian@ysten.com
 *  @date: 2020/8/19 18:23
 */
class RecycleShimmerFragment(b: Boolean = false) : Fragment() {
    init {
        arguments = bundleOf("image" to b)
    }

    private val userImageOnly by lazy { arguments?.getBoolean("image") ?: false }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = RecyclerView(inflater.context)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val rv = view as RecyclerView
        val images = listOf(
            "https://wx4.sinaimg.cn/mw690/5ba8d1cbly3ghv1ynzcaoj20go0gon4y.jpg",
            "https://wx2.sinaimg.cn/mw690/5ba8d1cbly3ghv1yo5ippj20u00u0tds.jpg",
            "https://wx4.sinaimg.cn/mw690/5ba8d1cbly3ghv1yni2tgj20u00u0h0c.jpg",
            "https://wx4.sinaimg.cn/mw690/acff3e61ly1ghvvq3lfrmj21o02804qr.jpg",
            "https://wx4.sinaimg.cn/mw690/acff3e61ly1ghvvq3lfrmj21o02804qr.jpg",
            "https://wx2.sinaimg.cn/mw690/daade500ly1ghv6p13yegj20zk0qo7wh.jpg",
//            "android.resource://${requireContext().packageName}/raw/a.gif",
//            "android.resource://${requireContext().packageName}/raw/b.gif",

//            "https://p2.ssl.qhimgs1.com/sdr/400__/t0146a8774d8a3933d8.gif"
//            "http://p0.ssl.qhimgs1.com/sdr/400__/t010e7771b60b3ad896.gif",
            "https://wx2.sinaimg.cn/mw690/daade500ly1ghv6p13yegj20zk0qo7wh.jpg"
        )
        rv.addItemDecoration(object : RecyclerView.ItemDecoration() {

            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.bottom = 30;
            }

            val p = Paint().apply {
                color =Color.RED
            }
            override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
                super.onDrawOver(c, parent, state)
                for (child in parent.children) {
                    val top = child.bottom.toFloat()
                    val bottom = child.bottom +2f
                    c.drawRect(left.toFloat(), top, right.toFloat(), bottom, p)
                }
            }
        })


        rv.layoutManager = LinearLayoutManager(view.context)
        rv.adapter = Adapter(images, userImageOnly)
        rv.clipChildren = false
        rv.clipToPadding = false


    }


    class Adapter(val list: List<String>, private val userImage: Boolean) :
        RecyclerView.Adapter<Adapter.VH>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
            val v =
                if (userImage) SimpleImage(parent.context) else CanvasShimmerView(parent.context)
            return VH(v.apply {
                layoutParams = RecyclerView.LayoutParams(200, 200).apply {
                    setMargins(200, 0, 200, 0)
                }
            })
        }

        override fun onBindViewHolder(holder: VH, position: Int) {
            holder.bind(position, list.get(position % list.size))
        }

        override fun getItemCount() = 1000

        class VH(private val iv: View) : RecyclerView.ViewHolder(iv) {
            init {
                iv.isFocusable = true
                iv.isFocusableInTouchMode = true
                iv.setOnHoverListener(HoverListener)
                iv.onFocusChangeListener = FocusListener
                iv.setOnClickListener {
                    iv.requestFocus()
                }
            }

            val tv by lazy { iv as UriImageView }
            fun bind(position: Int, url: String) {
                if (position == 0) {
                    tv.hierarchy.roundingParams = RoundingParams.asCircle()
                }
                tv.controller = newController(url)
                println("bound ${tv.hierarchy}")
            }

            private fun newController(url: String): DraweeController {
                return Fresco.newDraweeControllerBuilder()
                    .setUri(url)
                    .setAutoPlayAnimations(true)
                    .setImageRequest(let {
                        ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
                            .setResizeOptions(ResizeOptions(200, 200))
                            .build()
                    })
                    .build();
            }


        }

    }
}